const fs = require('fs')
const {
	promisify
} = require('util')

const unlinkAsync = promisify(fs.unlink)
var express = require('express')
var multer = require('multer')
var path = require('path')
var router = express.Router()
var bodyParser = require('body-parser')

//创建application/json解析
var jsonParser = bodyParser.json()

// 更改大文件的存储路径
var createFolder = function(folder) {
	try {
		fs.accessSync(folder)
	} catch (e) {
		fs.mkdirSync(folder)
	}
}

// 设定存储文件夹为当前目录下的 /upload 文件夹
const uploadFolder = '../upload'
createFolder(uploadFolder)

const upload = multer({
	dest: path.join(__dirname, `../${uploadFolder}`)
})

const routerList = [
	{
		name: '上传页面',
		path: '/',
		components: '../views/home.html'
	},
	{
		name: '单文件上传',
		path: '/upload',
		components: '../views/upload.html'
	},
	{
		name: '多文件上传',
		path: '/uploadFile',
		components: '../views/uploadFile.html'
	},
	{
		name: '文件夹上传',
		path: '/uploadFiles',
		components: '../views/uploadFiles.html'
	},
	{
		name: '列表页面',
		path: '/filelist',
		components: '../views/filelist.html'
	}
]


routerList.forEach(item => {
	router.get(item.path, (req, res) => {
		res.sendFile(path.join(__dirname, item.components))
	})
})

// 单/多文件上传
router.post('/upload', upload.array('file', 800), function(req, res) {
	var paths = []
	if (req.files.length === 0) {
		res.json({
			status: 400,
			message: '请选择要上传的文件！',
		})
		return false
	} else {
		for (var i = 0; i < req.files.length; i++) {
			var path = req.files[i].path.replace(/\\/g, '/')
			paths.push(path)
		}
		res.json({
			status: 200,
			message: '上传成功',
			fileurls: paths,
		})
	}
})

// 文件目录上传
router.post('/uploads', upload.array('file'), async (req, res) => {
	let paths = []
	const params = req.body.directory
	const fileLists = req.files;
	params.forEach((item, idx) => {
		const des = fileLists[idx]['destination'].replace(/\\/g, '/')
		const path = fileLists[idx]['path'].replace(/\\/g, '/')
		const name = fileLists[idx]['originalname']
		const desPath = `${des}/${item}${name}`
		const desName = `${des}/${name}`
		fs.rename(path, desName, (err) => {
			if (err) console.log('失败')
			else {
				uploadsPath(`${des}/${item}`, desName, desPath);
			}
		});
		paths.push({
			name,
			path: desPath,
			size: fileLists[idx]['size']
		})
	})
	res.json({
		status: 200,
		message: '上传成功',
		fileurls: paths,
	})
})

async function uploadsPath(path, desName, desPath) {
	await dirExists(path);
	fs.rename(desName, desPath, (err) => {
		if (err) console.log('失败2')
	});
}

router.post('/uploadFiles', function(req, res) {
	console.log('____________')
	console.log('req.files::', req)
	console.log('req.files::', req.body)
	console.log('req.files::', req.params)
	console.log('req.files::', req.files)
	console.log('____________')
	res.json({
		status: 200,
		message: '上传成功',
	})
})

// 下载文件
router.get('/download', function(req, res) {
	var filePath = req.query.path
	console.log('下载文件：' + filePath)
	filePath = path.join(__dirname, '../' + filePath)
	res.attachment(filePath)
	res.sendFile(filePath)
})

// 删除文件
router.post('/delete', jsonParser, function(req, res, next) {
	var filePath = req.body.filePath
	try {
		fs.unlinkSync(filePath)
		res.send('删除成功')
	} catch (error) {
		res.send('删除失败')
	}
})

// 获取文件列表
router.get('/getFileList', function(req, res, next) {
	var filelist = getFileList(uploadFolder)
	res.send(filelist)
})

function getFileList(path) {
	var filelist = []
	readFile(path, filelist)
	return filelist
}

function readFile(path, filelist) {
	var files = fs.readdirSync(path)
	files.forEach(walk)

	function walk(file) {
		var state = fs.statSync(path + '/' + file)
		if (state.isDirectory()) {
			readFile(path + '/' + file, filelist)
		} else {
			var obj = new Object()
			obj.size = state.size
			obj.name = file
			obj.path = path + '/' + file
			filelist.push(obj)
		}
	}
}


/**
 * 读取路径信息
 * @param {string} path 路径
 */
function getStat(path) {
	return new Promise((resolve, reject) => {
		fs.stat(path, (err, stats) => {
			if (err) {
				resolve(false);
			} else {
				resolve(stats);
			}
		})
	})
}

/**
 * 创建路径
 * @param {string} dir 路径
 */
function mkdir(dir) {
	return new Promise((resolve, reject) => {
		fs.mkdir(dir, err => {
			if (err) {
				resolve(false);
			} else {
				resolve(true);
			}
		})
	})
}

/**
 * 路径是否存在，不存在则创建
 * @param {string} dir 路径
 */
async function dirExists(dir) {
	let isExists = await getStat(dir);
	//如果该路径且不是文件，返回true
	if (isExists && isExists.isDirectory()) {
		return true;
	} else if (isExists) { //如果该路径存在但是文件，返回false
		return false;
	}
	//如果该路径不存在
	let tempDir = path.parse(dir).dir; //拿到上级路径
	//递归判断，如果上级目录也不存在，则会代码会在此处继续循环执行，直到目录存在
	let status = await dirExists(tempDir);
	let mkdirStatus;
	if (status) {
		mkdirStatus = await mkdir(dir);
	}
	return mkdirStatus;
}

module.exports = router
